iT邦幫忙

0

為了轉生而點技能-JavaScript,day21(let、const介紹

  • 分享至 

  • xImage
  •  

Var:作用域是依照所屬的函式位於的區塊內,且可以重複宣告。

        for (var i = 0; i < 3; i++) {
        };
        console.log(i);            //3

        (function () {
            for (var j = 0; j < 3; j++) {

            };
        }());
        console.log(j);             //j is not defined
        
        
        var boy = 'TOM';
        var boy = 'BOB';
        console.log(boy);           //BOB



let:作用域是依照所屬{}區塊內,且不可以重複宣告。

        for (let i = 0; i < 3; i++) {
            console.log(i);                //0 1 2
        };
        console.log(i);                    //i is not defined

        (function () {
            for (var j = 0; j < 3; j++) {

            };
        }());
        console.log(j);             //j is not defined
        
        
        var boy = 'TOM';
        var boy = 'BOB';
        console.log(boy);           //Identifier 'boy' has already been declared
        
        
        {
            let boy = 'TOM';
            console.log(boy);       //TOM
        };
        let boy = 'BOB';
        console.log(boy);           //BOB

TDZ(暫時性死區):let一樣會有hoisting,但是在創造階段,無法呼叫變數;如果是var,則會出現該變數是undefined的值。




const:作用域是依照所屬{}區塊內,且不可以重複宣告,或是重複賦值;如果內容(值)是個物件,那麼此物件的內容(物件的參數)是可以更改的。

        var boy = 'TOM';
        boy = 'BOB';
        console.log(boy);     //BOB
        
        
        let boy = 'TOM';
        boy = 'BOB';
        console.log(boy);     //BOB
        
        
        const boy = 'TOM';
        boy = 'BOB';
        console.log(boy);     //Uncaught TypeError: Assignment to constant variable.
        
        
        const family = {
            father: 'TOM',
            mothetr: 'Mar',
        };

        family.father = 'Park'
        console.log(family.father);  //Park
        
        family = {};                //Uncaught TypeError: Assignment to constant variable.
        
        
        
        
        
        
        
        

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言